//
//  WKWebViewController.m
//  WKWebViewOC
//
//  Created by XiaoFeng on 2016/11/24.
//  Copyright © 2016年 XiaoFeng. All rights reserved.
//  QQ群: 384089763 欢迎加入
//  github链接: https://github.com/XFIOSXiaoFeng/WKWebView


#import "WKWebViewController.h"

#import <WebKit/WKWebView.h>
#import <WebKit/WebKit.h>
#import <AlipaySDK/AlipaySDK.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "APAuthInfo.h"
#import "APOrderInfo.h"
#import "GTMBase64.h"
#import "WXApiManager.h"
#import "WXApiRequestHandler.h"

#define kIsIphone_X [UIScreen mainScreen].bounds.size.height == 812
// 导航栏和状态栏总高度 导航栏一直是44 X状态栏一直是44 其他机型正常是20 打电话时增加了20 20或40
#define kNavMaxY (kIsIphone_X ? (44 + [UIApplication sharedApplication].statusBarFrame.size.height) : (44 + [UIApplication sharedApplication].statusBarFrame.size.height))


typedef enum{
    loadWebURLString = 0,
    loadWebHTMLString,
    POSTWebURLString,
}wkWebLoadType;

static void *WkwebBrowserContext = &WkwebBrowserContext;

@interface WKWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UINavigationBarDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) WKWebView *wkWebView;
//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
//仅当第一次的时候加载本地JS
@property(nonatomic,assign) BOOL needLoadJSPOST;
//网页加载的类型
@property(nonatomic,assign) wkWebLoadType loadType;
//保存的网址链接
@property (nonatomic, copy) NSString *URLString;
//保存POST请求体
@property (nonatomic, copy) NSString *postData;
//保存请求链接
@property (nonatomic)NSMutableArray* snapShotsArray;
////返回按钮
//@property (nonatomic)UIBarButtonItem* customBackBarItem;
////关闭按钮
//@property (nonatomic)UIBarButtonItem* closeButtonItem;

@end

@implementation WKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //加载web页面
    [self webViewloadURLType];
    
    //添加到主控制器上
    [self.view addSubview:self.wkWebView];
    
    //添加进度条
    [self.view addSubview:self.progressView];
    
    //添加右边刷新按钮
    UIBarButtonItem *roadLoad = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(roadLoadClicked)];
    self.navigationItem.rightBarButtonItem = roadLoad;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    UIButton * ce = [UIButton buttonWithType:UIButtonTypeCustom];
    ce.backgroundColor = [UIColor yellowColor];
    ce.frame = CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height - 49, self.view.frame.size.width/4, 49);
    [ce addTarget:self action:@selector(ceClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:ce];
}

- (void)ceClick{
    NSLog(@"点击了");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (_isNavHidden == YES) {
        self.navigationController.navigationBarHidden = YES;
        //创建一个高20的假状态栏
        UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
        //设置成绿色
        statusBarView.backgroundColor=[UIColor whiteColor];
        // 添加到 navigationBar 上
        [self.view addSubview:statusBarView];
    }else{
        self.navigationController.navigationBarHidden = NO;
    }
}


- (void)roadLoadClicked{
    [self.wkWebView reload];
}

-(void)customBackItemClicked{
    if (self.wkWebView.goBack) {
        [self.wkWebView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)closeItemClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ================ 加载方式 ================

- (void)webViewloadURLType{
    switch (self.loadType) {
        case loadWebURLString:{
            //创建一个NSURLRequest 的对象
            NSURLRequest * Request_zsj = [NSURLRequest requestWithURL:[NSURL URLWithString:self.URLString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
            //加载网页
            [self.wkWebView loadRequest:Request_zsj];
            break;
        }
        case loadWebHTMLString:{
            [self loadHostPathURL:self.URLString];
            break;
        }
        case POSTWebURLString:{
            // JS发送POST的Flag，为真的时候会调用JS的POST方法
            self.needLoadJSPOST = YES;
            //POST使用预先加载本地JS方法的html实现，请确认WKJSPOST存在
            [self loadHostPathURL:@"WKJSPOST"];
            break;
        }
    }
}

- (void)loadHostPathURL:(NSString *)url{
    //获取JS所在的路径
    NSString *path = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
    //获得html内容
    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //加载js
    [self.wkWebView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
}

// 调用JS发送POST请求
- (void)postRequestWithJS {
    // 拼装成调用JavaScript的字符串
    NSString *jscript = [NSString stringWithFormat:@"post('%@',{%@});", self.URLString, self.postData];
    // 调用JS代码
    [self.wkWebView evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) {
    }];
}


- (void)loadWebURLSring:(NSString *)string{
    self.URLString = string;
    self.loadType = loadWebURLString;
}

- (void)loadWebHTMLSring:(NSString *)string{
    self.URLString = string;
    self.loadType = loadWebHTMLString;
}

- (void)POSTWebURLSring:(NSString *)string postData:(NSString *)postData{
    self.URLString = string;
    self.postData = postData;
    self.loadType = POSTWebURLString;
}

#pragma mark ================ 自定义返回/关闭按钮 ================

-(void)updateNavigationItems{
    if (self.wkWebView.canGoBack) {
        UIBarButtonItem *spaceButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        spaceButtonItem.width = -6.5;

//        [self.navigationItem setLeftBarButtonItems:@[spaceButtonItem,self.customBackBarItem,self.closeButtonItem] animated:NO];
    }else{
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
//        [self.navigationItem setLeftBarButtonItems:@[self.customBackBarItem]];
    }
}
//请求链接处理
-(void)pushCurrentSnapshotViewWithRequest:(NSURLRequest*)request{
    
    NSString * url = [NSString stringWithFormat:@"%@",request.URL];
    if ([url isEqualToString:@"http://gopay.com/"]){
        
       
        
        return;
    }
    
        NSLog(@"push with request %@",request.URL);
    NSURLRequest* lastRequest = (NSURLRequest*)[[self.snapShotsArray lastObject] objectForKey:@"request"];
    
    //如果url是很奇怪的就不push
    if ([request.URL.absoluteString isEqualToString:@"http://gopay.com/"]) {
        NSLog(@"about blank!! return");
        return;
    }
    
    //如果url一样就不进行push
    if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) {
        return;
    }
    UIView* currentSnapShotView = [self.wkWebView snapshotViewAfterScreenUpdates:YES];
    [self.snapShotsArray addObject:
     @{@"request":request,@"snapShotView":currentSnapShotView}];
}

#pragma mark ================ WKNavigationDelegate ================

//这个是网页加载完成，导航的变化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString * string = [NSString stringWithFormat:@"getUserAgen('%@')",@"iOS"];
    [self.wkWebView evaluateJavaScript:string completionHandler:^(id item, NSError *error) {
        NSLog(@"结果：%@",item);
        
    }];
    
    /*
     主意：这个方法是当网页的内容全部显示（网页内的所有图片必须都正常显示）的时候调用（不是出现的时候就调用），，否则不显示，或则部分显示时这个方法就不调用。
     */
    // 判断是否需要加载（仅在第一次加载）
    if (self.needLoadJSPOST) {
        // 调用使用JS发送POST请求的方法
        [self postRequestWithJS];
        // 将Flag置为NO（后面就不需要加载了）
        self.needLoadJSPOST = NO;
    }
    // 获取加载网页的标题
    self.title = self.wkWebView.title;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateNavigationItems];
}

//开始加载
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    //开始加载的时候，让加载进度条显示
    
    
    
    self.progressView.hidden = NO;
}

//内容返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{}

//服务器请求跳转的时候调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
    NSLog(@"123");
    
}

//服务器开始请求的时候调用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *mobileUrl = [[navigationAction.request URL] absoluteString];
    mobileUrl = [mobileUrl stringByRemovingPercentEncoding];
    if ([mobileUrl isEqualToString:@"http://testgt.caibangw.com:8880/#/home"]) {
        
    }else if([mobileUrl isEqualToString:@"http://photo.com/"]){
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"选择" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"OK Action");
            [self pictureBtnClick];
        }];
        UIAlertAction * Action = [UIAlertAction actionWithTitle:@"在线拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePictureClick];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"Cancel Action");
            
        }];
        [alertController addAction:okAction]; // A
        [alertController addAction:Action]; // A
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }else if ([mobileUrl isEqualToString:@"http://tel.com/"]){//拨打电话
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.wkWebView evaluateJavaScript:@"javascript:exportTel()" completionHandler:^(id item, NSError *error) {
            NSLog(@"结果：%@",item);
            NSMutableString *str=[[NSMutableString alloc]initWithFormat:@"tel:%@",item];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }];
        return;
    }else if ([mobileUrl isEqualToString:@"https://www.gopay.com/"]) {//订单支付
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.wkWebView evaluateJavaScript:@"javascript:exportPay()" completionHandler:^(id item, NSError *error) {//submitpay
            NSLog(@"结果：%@",item);
            NSArray * array = item;
            NSLog(@"数组：%@",array);
            //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
            NSString *appScheme = @"cbbUrlWeb";
            if(array.count >= 2){
                if ([array[0] isEqualToString:@"alipay"]){
                    [[AlipaySDK defaultService] payOrder:array[1][@"sign"] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                        NSLog(@"reslut = %@",resultDic);
                        NSString * strTitle = [NSString stringWithFormat:@"支付结果"];
                        NSString *strMsg;
                        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                            self.tabBarController.selectedIndex = 2;
                            [self.navigationController popToRootViewControllerAnimated:YES];
                            strMsg = @"恭喜您，支付成功!";
                        }else if([resultDic[@"resultStatus"] isEqualToString:@"6001"]){
                            strMsg = @"已取消支付!";
                        }else{
                            strMsg = @"支付失败!";
                        }
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        
//                        [alert show];
                    }];
                }else if([array[0] isEqualToString:@"wx"]) {
                    NSDictionary * orderDic = array[1];
                    NSMutableString *stamp  = [NSMutableString stringWithFormat:@"%@",[orderDic objectForKey:@"timestamp"]];
                    PayReq *request = [[PayReq alloc] init];
                    request.partnerId = orderDic[@"partnerid"];
                    request.prepayId= orderDic[@"prepayid"];
                    request.package = orderDic[@"package"];
                    request.nonceStr= orderDic[@"noncestr"];
                    request.timeStamp = [stamp intValue];
                    request.sign = orderDic[@"sign"];
                    [WXApi sendReq:request];
                }
            }
            
        }];
        
        return;
    }else if ([mobileUrl isEqualToString:@"https://www.gorecharge.com/"]) {//充值
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.wkWebView evaluateJavaScript:@"javascript:exportRecharge()" completionHandler:^(id item, NSError *error) {//submitpay
            NSLog(@"结果：%@",item);
            NSArray * array = item;
            NSLog(@"数组：%@",array);
            //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
            NSString *appScheme = @"cbbUrlWeb";
            if(array.count >= 2){
                if ([array[0] isEqualToString:@"alipay"]){
                    [[AlipaySDK defaultService] payOrder:array[1] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                        NSLog(@"reslut = %@",resultDic);
                        NSString * strTitle = [NSString stringWithFormat:@"支付结果"];
                        NSString *strMsg;
                        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                            self.tabBarController.selectedIndex = 2;
                            [self.navigationController popToRootViewControllerAnimated:YES];
                            strMsg = @"恭喜您，支付成功!";
                        }else if([resultDic[@"resultStatus"] isEqualToString:@"6001"]){
                            strMsg = @"已取消支付!";
                        }else{
                            strMsg = @"支付失败!";
                        }
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        
//                        [alert show];
                    }];
                }else if([array[0] isEqualToString:@"wx"]) {
                    NSDictionary * orderDic = array[1];
                    NSMutableString *stamp  = [NSMutableString stringWithFormat:@"%@",[orderDic objectForKey:@"timestamp"]];
                    PayReq *request = [[PayReq alloc] init];
                    request.partnerId = orderDic[@"partnerid"];
                    request.prepayId= orderDic[@"prepayid"];
                    request.package = orderDic[@"package"];
                    request.nonceStr= orderDic[@"noncestr"];
                    request.timeStamp = [stamp intValue];
                    request.sign = orderDic[@"sign"];
                    [WXApi sendReq:request];
                }
            }
            
        }];
        
        return;
    }else if ([mobileUrl isEqualToString:@"http://goplus.com/"]) {//购买会员
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.wkWebView evaluateJavaScript:@"javascript:exportPluspay()" completionHandler:^(id item, NSError *error) {//submitpay
            NSLog(@"结果：%@",item);
            NSArray * array = item;
            NSLog(@"数组：%@",array);
            //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
            NSString *appScheme = @"cbbUrlWeb";
            if(array.count >= 2){
                if ([array[0] isEqualToString:@"alipay"]){
                    [[AlipaySDK defaultService] payOrder:array[1] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                        NSLog(@"reslut = %@",resultDic);
                        NSString * strTitle = [NSString stringWithFormat:@"支付结果"];
                        NSString *strMsg;
                        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                            self.tabBarController.selectedIndex = 2;
                            [self.navigationController popToRootViewControllerAnimated:YES];
                            strMsg = @"恭喜您，支付成功!";
                        }else if([resultDic[@"resultStatus"] isEqualToString:@"6001"]){
                            strMsg = @"已取消支付!";
                        }else{
                            strMsg = @"支付失败!";
                        }
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        
                        [alert show];
                    }];
                }else if([array[0] isEqualToString:@"wx"]) {
                    NSDictionary * orderDic = array[1];
                    NSMutableString *stamp  = [NSMutableString stringWithFormat:@"%@",[orderDic objectForKey:@"timestamp"]];
                    PayReq *request = [[PayReq alloc] init];
                    request.partnerId = orderDic[@"partnerid"];
                    request.prepayId= orderDic[@"prepayid"];
                    request.package = orderDic[@"package"];
                    request.nonceStr= orderDic[@"noncestr"];
                    request.timeStamp = [stamp intValue];
                    request.sign = orderDic[@"sign"];
                    [WXApi sendReq:request];
                }
            }
            
        }];
        
        return;
    }

    switch (navigationAction.navigationType) {
            
        case WKNavigationTypeLinkActivated: {
                [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
            
            break;
        }
        case WKNavigationTypeFormSubmitted: {

                [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
            
            break;
        }
        case WKNavigationTypeBackForward: {
            break;
        }
        case WKNavigationTypeReload: {
            break;
        }
        case WKNavigationTypeFormResubmitted: {
            break;
        }
        case WKNavigationTypeOther: {
                [self pushCurrentSnapshotViewWithRequest:navigationAction.request];
            
            break;
        }
        default: {
            break;
        }
            
    }
    [self updateNavigationItems];
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 内容加载失败时候调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
//    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"地址加载失败" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//
//    }];
//    UIAlertAction * okAlert = [UIAlertAction actionWithTitle:@"返回上一页" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
//    [alert addAction:cancel];
//    [alert addAction:okAlert];
//    [self presentViewController:alert animated:YES completion:^{
    
//    }];
    NSLog(@"页面加载超时");
}

//跳转失败的时候调用
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{}

//进度条
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{}


//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark ================ 懒加载 ================

- (WKWebView *)wkWebView{
    if (!_wkWebView) {
        //设置网页的配置文件
        WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
        //允许视频播放
        Configuration.allowsAirPlayForMediaPlayback = YES;
        // 允许在线播放
        Configuration.allowsInlineMediaPlayback = YES;
        // 允许可以与网页交互，选择视图
        Configuration.selectionGranularity = YES;
        // web内容处理池
        Configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
        // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
//        [UserContentController addScriptMessageHandler:self name:@"WXPay"];
        // 是否支持记忆读取
        Configuration.suppressesIncrementalRendering = YES;
        // 允许用户更改网页的设置
        Configuration.userContentController = UserContentController;
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kNavMaxY - 44, self.view.frame.size.width, self.view.frame.size.height - kNavMaxY + 44) configuration:Configuration];
        _wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
        // 设置代理
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        //kvo 添加进度监控
        [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];
        //开启手势触摸
//        _wkWebView.allowsBackForwardNavigationGestures = YES;
        // 设置 可以前进 和 后退
        //适应你设定的尺寸
//        [_wkWebView sizeToFit];
    }
    return _wkWebView;
}

- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        if (_isNavHidden == YES) {
            _progressView.frame = CGRectMake(0, 20, self.view.bounds.size.width, 3);
        }else{
            _progressView.frame = CGRectMake(0, 20, self.view.bounds.size.width, 3);
        }
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor greenColor];
    }
    return _progressView;
}


-(void)viewWillDisappear:(BOOL)animated{
    [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"WXPay"];
//    [self.wkWebView setNavigationDelegate:nil];
//    [self.wkWebView setUIDelegate:nil];
}

//注意，观察的移除
-(void)dealloc{
    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}

//调用相机
- (void)takePictureClick{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *pic = [[UIImagePickerController alloc] init];
        pic.sourceType = UIImagePickerControllerSourceTypeCamera;
        pic.allowsEditing = YES;
        pic.showsCameraControls = YES;
        pic.delegate =self;
        [self presentViewController:pic animated:YES completion:nil];
    }
}

//相册选取图片
- (void)pictureBtnClick{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    ipc.allowsEditing = YES;
    ipc.delegate =self;
    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark - ImagePickerDelegate

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
    
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    //    _imageView.image = newImage;
    
    return newImage;
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"info ---%@",info);
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    CGSize imagesize = image.size;
    imagesize.height =100;
    imagesize.width =100;
    UIImage *img = [self imageWithImage:image scaledToSize:imagesize];
    NSLog(@"image -- %f",img.size.width);
    [self updateUserHeaderWithImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)updateUserHeaderWithImage:(UIImage *)image {
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *imageStr = [GTMBase64 stringByEncodingData:imageData];
    NSString * string = [NSString stringWithFormat:@"exportPho('%@')",imageStr];
    [self.wkWebView evaluateJavaScript:string completionHandler:^(id item, NSError *error) {
        NSLog(@"结果：%@",item);
        
    }];
}

@end
